<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="queryParams.jobName" placeholder="请输入jobName" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="任务组名" prop="jobGroup">
              <el-input v-model="queryParams.jobGroup" placeholder="请输入jobGroup" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="定时名称" prop="methodName">
              <el-input v-model="queryParams.methodName" placeholder="请输入methodName" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <!-- <el-form-item label="方法参数" prop="methodParams">
              <el-input v-model="queryParams.methodParams" placeholder="请输入methodParams" clearable
                @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="cron" prop="cronExpression">
              <el-input v-model="queryParams.cronExpression" placeholder="请输入cron" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="queryParams.serviceName" placeholder="请输入服务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="服务方法" prop="serviceMethod">
              <el-input v-model="queryParams.serviceMethod" placeholder="请输入服务方法" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>

              <!-- 新增获取 cron 表达式的表单元素
              <el-input v-model="cronForm.methodName" placeholder="定时名称" clearable
                style="width: 120px; margin-left: 10px;" />
              <el-input v-model="cronForm.serviceName" placeholder="服务名称" clearable
                style="width: 120px; margin-left: 5px;" />
              <el-input v-model="cronForm.serviceMethod" placeholder="服务方法" clearable
                style="width: 120px; margin-left: 5px;" /> -->
              <!-- <el-button type="info" @click="getCronExpressionHandler" style="margin-left: 5px;">开启定时任务</el-button>
              <el-button type="info" @click="handleStopOneTask" style="margin-left: 5px;">停止定时任务</el-button>
              <el-button type="info" @click="handleStopAllTasks" style="margin-left: 5px;">停止所有定时任务</el-button> -->
              <!-- <el-tooltip content="开启定时任务" placement="top">
                <el-button type="success" icon="Check" @click="getCronExpressionHandler" style="margin-left: 10px;"
                  round>
                  启 动
                </el-button>
              </el-tooltip>

              <el-tooltip content="停止当前配置任务" placement="top">
                <el-button type="warning" icon="SwitchButton" @click="handleStopOneTask" style="margin-left: 10px;"
                  round>
                  停 止
                </el-button>
              </el-tooltip>

              <el-tooltip content="停止所有定时任务" placement="top">
                <el-button type="danger" icon="Close" @click="handleStopAllTasks" style="margin-left: 10px;" round>
                  全停
                </el-button>
              </el-tooltip> -->
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['job:job:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['job:job:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['job:job:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['job:job:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="SysJobList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="jobId" align="center" prop="jobId" v-if="true" />
        <el-table-column label="任务名称" align="center" prop="jobName" />
        <!-- <el-table-column label="任务组名" align="center" prop="jobGroup" /> -->
        <el-table-column label="定时名称" align="center" prop="methodName" />
        <!-- <el-table-column label="方法参数" align="center" prop="methodParams" /> -->
        <el-table-column label="cron" align="center" prop="cronExpression" />
        <!-- <el-table-column label="并发执行" align="center" prop="concurrent" /> -->
        <el-table-column label="服务名称" align="center" prop="serviceName" />
        <el-table-column label="服务方法" align="center" prop="serviceMethod" />
        <el-table-column label="任务状态" align="center" prop="status" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['job:job:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['job:job:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="开启任务" placement="top">
              <el-button
                link
                type="primary"
                icon="VideoPlay"
                @click="handleToggleTask(scope.row, 'start')"
                v-hasPermi="['job:job:start']"
              ></el-button>
            </el-tooltip>

            <el-tooltip content="关闭任务" placement="top">
              <el-button link type="danger" icon="CircleClose" @click="handleToggleTask(scope.row, 'stop')" v-hasPermi="['job:job:stop']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改股票信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="SysJobFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="form.jobName" placeholder="请输入jobName" />
        </el-form-item>

        <el-form-item label="任务组名" prop="jobGroup">
          <el-input v-model="form.jobGroup" placeholder="系统默认（有参）可不写" />
        </el-form-item>

        <el-form-item label="定时名称" prop="methodName">
          <el-input v-model="form.methodName" placeholder="请输入methodName" />
        </el-form-item>

        <!-- <el-form-item label="方法参数" prop="methodParams">
          <el-input v-model="form.methodParams" placeholder="请输入methodParams" />
        </el-form-item> -->

        <el-form-item label="cron" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="请输入cronExpression" />
        </el-form-item>

        <!-- <el-form-item label="并发执行" prop="concurrent">
          <el-input v-model="form.concurrent" placeholder="0允许|1禁止" />
        </el-form-item> -->
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入serviceName" />
        </el-form-item>
        <el-form-item label="服务方法" prop="serviceMethod">
          <el-input v-model="form.serviceMethod" placeholder="请输入serviceMethod" />
        </el-form-item>
        <!-- <el-form-item label="任务状态" prop="status">
          <el-input v-model="form.status" placeholder="0无" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysJob" lang="ts">
import { listSysJob, getSysJob, delSysJob, addSysJob, updateSysJob, getCronExpression, stopTask, stopAllTasks } from '@/api/job/job';
import { SysJobVO, SysJobQuery, SysJobForm } from '@/api/job/job/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const SysJobList = ref<SysJobVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const SysJobFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SysJobForm = {
  jobId: undefined,
  jobName: undefined,
  jobGroup: undefined,
  methodName: undefined,
  // methodParams: undefined,
  cronExpression: undefined,
  // concurrent: undefined,
  serviceName: undefined,
  serviceMethod: undefined,
  status: undefined
};
const data = reactive<PageData<SysJobForm, SysJobQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    jobName: undefined,
    jobGroup: undefined,
    methodName: undefined,
    // methodParams: undefined,
    cronExpression: undefined,
    // concurrent: undefined,
    serviceName: undefined,
    serviceMethod: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    jobId: [{ required: true, message: 'ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询股票信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSysJob(queryParams.value);
  SysJobList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  SysJobFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SysJobVO[]) => {
  ids.value = selection.map((item) => item.jobId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加股票信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SysJobVO) => {
  reset();
  const _id = row?.jobId || ids.value[0];
  const res = await getSysJob(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改股票信息';
};

/** 提交按钮 */
const submitForm = () => {
  SysJobFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.jobId) {
        await updateSysJob(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSysJob(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SysJobVO) => {
  const _ids = row?.jobId || ids.value;
  await proxy?.$modal.confirm('是否确认删除股票信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delSysJob(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

// 定义响应式数据
const cronForm = ref({
  methodName: '',
  serviceName: '',
  serviceMethod: ''
});
const cronResult = ref('');
// 定义获取 cron 表达式的函数
const getCronExpressionHandler = async () => {
  if (!cronForm.value.methodName || !cronForm.value.serviceName || !cronForm.value.serviceMethod) {
    proxy?.$modal.msgWarning('请填写完整参数');
    return;
  }
  try {
    await proxy?.$modal.confirm(`确认开启任务 ${cronForm.value.serviceName}/${cronForm.value.serviceMethod}?`);
    const result = await getCronExpression(cronForm.value.methodName, cronForm.value.serviceName, cronForm.value.serviceMethod);
    cronResult.value = result.data;
    await getList();
    proxy?.$modal.msgSuccess('定时任务已开启');
  } catch (error) {
    proxy?.$modal.msgError('获取 cron 表达式失败');
    console.error('Error:', error);
  }
};

/**
 *  停止所有定时任务
 */
const handleStopAllTasks = async () => {
  try {
    await proxy?.$modal.confirm('确认停止所有定时任务?');
    await stopAllTasks();
    proxy?.$modal.msgSuccess('所有任务已停止');
    await getList();
  } catch (error) {
    proxy?.$modal.msgError('停止所有任务失败');
    console.error('停止所有任务失败:', error);
  }
};

/**
 * 停止单个定时任务
 */
const handleStopOneTask = async () => {
  if (!cronForm.value.serviceName || !cronForm.value.serviceMethod) {
    proxy?.$modal.msgWarning('请填写服务名称和服务方法');
    return;
  }
  try {
    await proxy?.$modal.confirm(`确认停止任务 ${cronForm.value.serviceName}/${cronForm.value.serviceMethod}?`);
    await stopTask(cronForm.value.serviceName, cronForm.value.serviceMethod);
    proxy?.$modal.msgSuccess('任务已停止');
    await getList();
  } catch (error) {
    proxy?.$modal.msgError('停止任务失败');
    console.error('停止任务失败:', error);
  }
};
// 开启/关闭任务的通用方法
const handleToggleTask = async (row, action) => {
  // 获取服务名称和服务方法
  // 获取全部三个参数
  cronForm.value.methodName = row.methodName;
  cronForm.value.serviceName = row.serviceName;
  cronForm.value.serviceMethod = row.serviceMethod;

  if (!cronForm.value.methodName || !cronForm.value.serviceName || !cronForm.value.serviceMethod) {
    proxy?.$modal.msgWarning('请填写完整参数');
    return;
  }

  try {
    if (action === 'start') {
      await proxy?.$modal.confirm(`确认开启任务 ${cronForm.value.serviceName}/${cronForm.value.serviceMethod}?`);
      const result = await getCronExpression(
        cronForm.value.methodName, // 添加 methodName 参数
        cronForm.value.serviceName,
        cronForm.value.serviceMethod
      );
      cronResult.value = result.data;
      proxy?.$modal.msgSuccess('定时任务已开启');
    } else if (action === 'stop') {
      // 确认停止任务
      await proxy?.$modal.confirm(`确认停止任务 ${cronForm.value.serviceName}/${cronForm.value.serviceMethod}?`);
      await stopTask(cronForm.value.serviceName, cronForm.value.serviceMethod);
      proxy?.$modal.msgSuccess('任务已停止');
    }
    await getList(); // 刷新任务列表
  } catch (error) {
    proxy?.$modal.msgError(action === 'start' ? '获取 cron 表达式失败' : '停止任务失败');
    console.error('Error:', error);
  }
};

onMounted(() => {
  getList();
});
</script>
